﻿#include "reportManager.h"


QString extractFileName(QString path){
    path.replace("\\", "/");
    return path.split("/").back();
}
QString extractPathName(QString path){
    QString filename = extractFileName(path);
    if(!filename.contains(".")){
        return path;
    }else{
        return path.mid(0, path.size() - filename.size());
    }
}

bool ReportManager::setGmiInterface(GetMessageInterface *gmi){

    __LOG_FSTART__;

    if(gmi == nullptr){
        __LOG_FEND("SetGmi-Failed");
        return false;
    }

    this->gmi = gmi;

    __LOG_FSTART("SetGmi-Succeed");
}

ReportManager::ReportManager()
{
    _exportType = WORD;
    _exportPath = "./datao";

    // 从数据库中获取默认导出路径
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql = "Select * From ExportInfo";
    query.exec(sql);
    int i = 0;
    while(query.next()){
        i ++;
        _exportPath = query.value("Path").toString();
        _exportType = (ExportType)query.value("Type").toInt();
    }
    if(i == 0){
        sql = QString("Insert Into ExportInfo Values ('%1', '%2')").arg(_exportPath, QString::number(_exportType));
        query.exec(sql);
    }


}

ReportManager& ReportManager::I(){
    static ReportManager instance;
    return instance;
}

int ReportManager::setReportIdx(int idx){
    qDebug() << "setReportIdx" << idx;
    __LOG_FSTART(idx);
    if(idx < 0){
        QSqlDatabase db = dbHelper::openConnection();
        QSqlQuery query(db);
        QString sql = "select serial, max(ExpEndTime) from ReportInfo";
        query.exec(sql);
        while (query.next()) {
            idx = query.value("serial").toInt();
        }
    }
    __LOG_DEBUG("CurrentReportManagerIdx:"+QString::number(idx));

    if(gmi==nullptr){
        __LOG_ERROR("gmi=nullptr");
        return 0;
    }

    _expInfo = gmi->getReportBaseInfo(idx);         // 这是啥玩意……这个gmi我怎么没赋值过啊……
    _logInfo = gmi->getReportDetail(idx);
    __LOG_FEND(idx);
    return idx;
}

bool ReportManager::setExportPath(QString path){

    __LOG_FSTART(path);

    qDebug() << "setPath" << path;
    QFile testAuthority(path+"/test.txt");
    bool res = testAuthority.open(QIODevice::ReadWrite);
    if(!res){
        return false;
    }
    testAuthority.remove();

    _exportPath = path;

    qDebug() << "setExportPath " + path;

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql = QString("Update ExportInfo Set Path='%1'").arg(path);
    query.exec(sql);

    __LOG_FEND__;

    return true;
}

bool ReportManager::setExportType(ExportType type){

    __LOG_FSTART(type);

    _exportType = type;

    qDebug() << QString("setExportType ") + type;

    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);
    QString sql = QString("Update ExportInfo Set Type='%1'").arg(QString::number(type));
    query.exec(sql);

    __LOG_FEND__;
    return true;
}

QString ReportManager::getExportPath(){
    return _exportPath;
}
int ReportManager::getExportType(){
    return _exportType;
}

int ReportManager::exportReport_auto(){

    if(_typeSuffix.size() <= _exportType){      // 校验
        __LOG_ERROR("typeSuffixLength:"+QString::number(_typeSuffix.size())+" _exportType:"+QString::number(_exportType));
        return -100;
    }

    // 自动导出时，多导出来一份到默认路径
    int res = exportReport("./report/autoExport_"+_expInfo["ExpStartTime"].toString()+".xlsx");
    return exportReport(_exportPath + "/" + QDateTime::currentDateTime().toString("yyyyMMddhhmmss") + _typeSuffix[_exportType]);
}

bool ReportManager::setAutoExport(bool state){
    _autoExport = state;
    return true;
}

bool ReportManager::getAutoExport(){
    return _autoExport;
}


int ReportManager::exportReport(QString path){

    __LOG_FSTART(path);


    path = path.replace("-", "_").replace(" ", "_").replace(":","_");

    int res = 1;

    // 已弃用，导出Word格式报告
//    WordExporter* we = new WordExporter;
//    res = we->exportWord(extractPathName(path), extractFileName(path), _expInfo, _logInfo);
//    delete we;

    // 导出Excel格式报告
    ExcelExporter* ee = new ExcelExporter;;
    path.replace(".docx", ".xlsx");
    res = ee->exportExcel(extractPathName(path), extractFileName(path), _expInfo, _logInfo);
    delete ee;

    __LOG_FEND(res);

    return res;
}

int ReportManager::exportReport(QString path, QVariantMap expInfo, QVariantList logInfo){

    int res = 1;

    // 自动导出word改为excel
//    WordExporter* we = new WordExporter;
//    res = we->exportWord(extractPathName(path), extractFileName(path), _expInfo, _logInfo);
//    delete we;

    ExcelExporter* ee = new ExcelExporter;;
    path.replace(".docx", ".xlsx");
    res = ee->exportExcel(extractPathName(path), extractFileName(path), expInfo, logInfo);
    delete ee;

    return res;
}

int ReportManager::exportReport_fileDialog(){
    QString path = QFileDialog::getSaveFileName(NULL, "导出报告", "/path/to/default/", "Excel(*.xlsx)");
    if(path == ""){
        return 1;
    }
    qDebug() << "ReportWordPath:" << path;
    if(!path.contains(".docx")){
        path.append(".docx");
    }
    return exportReport(path);
}

int ReportManager::exportReport_fileDialog(QVariantMap expInfo, QVariantList logInfo){

//    QString path = QFileDialog::getSaveFileName(NULL, "导出报告", "/path/to/default/", "Word(*.docx)");
    QString path = QFileDialog::getSaveFileName(NULL, "导出报告", "/path/to/default/", "Excel(*.xlsx)");
    if(path == ""){
        return 1;
    }
    qDebug() << "ReportWordPath:" << path;
    if(!path.contains(".docx")){
        path.append(".docx");
    }
    return exportReport(path, expInfo, logInfo);

}


bool ReportManager::updateExportInfo(QString path, int type, bool autoExport){

    type = std::max(0, std::min(2, type));
    if(!this->setExportPath(path)){
        return false;
    }
    this->setExportType(ReportManager::ExportType(type));
    this->setAutoExport(autoExport);
    return true;
}

void ReportManager::setReportInfo(QVariantMap expInfo, QVariantList logInfo){
    _expInfo = expInfo;
    _logInfo = logInfo;
}
QVariantMap ReportManager::getExperimentInfo(){
    return _expInfo;
}
QVariantList ReportManager::getLogInfo(){
    return _logInfo;
}

QString ReportManager::selectExportPath(){
    return QFileDialog::getExistingDirectory();
}




